/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.Sl;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.infor.entity.Rent;
import com.jeeplus.modules.infor.entity.RentPrice;
import com.jeeplus.modules.infor.service.RentPriceService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.entity.RentDetil;
import com.jeeplus.modules.infor.service.RentDetilService;

/**
 * 仓租收支明细Controller
 * @author 李超辉
 * @version 2018-09-28
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/rentDetil")
public class RentDetilController extends BaseController {

	@Autowired
	private RentDetilService rentDetilService;
	@Autowired
	private RentPriceService rentPriceService;
	@Autowired
	private SlService slService;
	
	@ModelAttribute
	public RentDetil get(@RequestParam(required=false) String id) {
		RentDetil entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = rentDetilService.get(id);
		}
		if (entity == null){
			entity = new RentDetil();
		}
		return entity;
	}
	
	/**
	 * 仓租收支明细列表页面
	 */
	@RequiresPermissions("infor:rentDetil:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/rentDetilList";
	}
	/**
	 * 仓租收支明细列表页面
	 */
	@RequestMapping(value ="list1")
	public String list1() {
		return "modules/infor/4/rentDetilList";
	}
	/**
	 * 仓租收支明细列表页面
	 */
	@RequestMapping(value ="list2")
	public String list2() {
		return "modules/infor/5/rentDetilList";
	}

	@RequestMapping(value = "cx")
	@ResponseBody
	public String cx(String min,String max,String pro){
		DecimalFormat df = new DecimalFormat("0.00%");
		NumberFormat nf = NumberFormat.getInstance();
		RentDetil r=new RentDetil();
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			r.setPro(pro);
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				r.setPro(UserUtils.getUseroffice());
			}
		}
      r.setMin(min);
		r.setQr(1);
		r.setMax(max);
		List<RentDetil> list=rentDetilService.findList(r);
		double zsr=0.0;
		double zzc=0.0;
		double zfk=0.0;
		String ids="";
		for(RentDetil  re:list){
			zsr+=Double.parseDouble(re.getZsr());
			zzc+=Double.parseDouble(re.getZzc());
			zfk+=Double.parseDouble(re.getFk());

			ids+=re.getId()+",";
		}
		double mlr=zsr-zzc;
		double lrl=mlr/zsr;
		r.setMax(ids);
		r.setFk(nf.format(zfk).replaceAll(",",""));
		r.setSr(nf.format(zsr).replaceAll(",",""));
		r.setZc(nf.format(zzc));
		r.setMlr(nf.format(mlr));
		r.setLrl(df.format(lrl));
		list.add(r);
		Gson g=new Gson();
		return g.toJson(list).toString() ;
	}


	@ResponseBody
	@RequestMapping(value="sd")
	public AjaxJson sd() throws Exception{
		AjaxJson j = new AjaxJson();
		Date d=new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.MONTH, -1);
		d=c.getTime();
		DecimalFormat df = new DecimalFormat("0.00%");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		NumberFormat nf = NumberFormat.getInstance();
		RentDetil rent=new RentDetil();
		rent.setDate(d);
		rent.setPro(UserUtils.getUseroffice());
		List<RentDetil> l=rentDetilService.findList(rent);
		if(l!=null&l.size()>0){
			j.setMsg("请勿重复计算");
			j.setSuccess(false);
			return j;
		}
			//仓租
			RentPrice r=new RentPrice();
			r.setMin(d);
			r.setMax(d);
		    r.setPro(UserUtils.getUseroffice());
			List<RentPrice> lis=rentPriceService.findList(r);
			Double sr=0.0;
			Double zc=0.0;
			Double srhs=0.0;
			Double zchs=0.0;
			double area=0.0;
			for(RentPrice ren:lis){
				if(ren.getType().equals("收入")){
					rent.setSrdj(ren.getPrice());
					rent.setSrad(ren.getAd());
					rent.setSl(ren.getSl());
					area+=Double.parseDouble(ren.getArea());
					srhs+=(Double.parseDouble(ren.getPrice())+Double.parseDouble(ren.getAd()))*Double.parseDouble(ren.getArea())*(Double.parseDouble(ren.getSl())+1);
					sr+=(Double.parseDouble(ren.getPrice())+Double.parseDouble(ren.getAd()))*Double.parseDouble(ren.getArea());
				}else{
					rent.setZcdj(ren.getPrice());
					rent.setZcfj(ren.getAd());
					zchs+=(Double.parseDouble(ren.getPrice())+Double.parseDouble(ren.getAd()))*Double.parseDouble(ren.getArea())*(Double.parseDouble(ren.getSl())+1);
					zc+=(Double.parseDouble(ren.getPrice())+Double.parseDouble(ren.getAd()))*Double.parseDouble(ren.getArea());
				}
			}
			rent.setStatus("已创建");
			rent.setSr(nf.format(sr).replaceAll(",",""));
			rent.setZc(nf.format(zc).replaceAll(",",""));
			rent.setZsr(nf.format(srhs).replaceAll(",",""));
			rent.setZzc(nf.format(zchs).replaceAll(",",""));
			rent.setFjsr("0");
			rent.setFjzc("0");
			rent.setFk("0");
			rent.setSrhs(nf.format(srhs).replaceAll(",",""));
			rent.setZchs(nf.format(zchs).replaceAll(",",""));
			rent.setArea(nf.format(area).replaceAll(",",""));

			rentDetilService.save(rent);

		j.setSuccess(true);
		j.setMsg("保存仓租收支明细成功");
		return j;
	}


	/**
	 * 仓租收支明细列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:rentDetil:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(RentDetil rentDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			rentDetil.setPro(pro);
		}
		Page<RentDetil> page = rentDetilService.findPage(new Page<RentDetil>(request, response), rentDetil);
		return getBootstrapData(page);
	}
	/**
	 * 仓租收支明细列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:rentDetil:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(RentDetil rentDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			rentDetil.setPro(pro);
		}
		rentDetil.setQr(1);
		Page<RentDetil> page = rentDetilService.findPage(new Page<RentDetil>(request, response), rentDetil);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑仓租收支明细表单页面
	 */
	@RequiresPermissions(value={"infor:rentDetil:view","infor:rentDetil:add","infor:rentDetil:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(RentDetil rentDetil, Model model) {
		if(rentDetil.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				rentDetil.setPro(pro);
				rentDetil.setStatus("已创建");
			}
		}
		model.addAttribute("rentDetil", rentDetil);
		return "modules/infor/rentDetilForm";
	}

	/**
	 * 保存仓租收支明细
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:rentDetil:add","infor:rentDetil:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(RentDetil rentDetil, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, rentDetil)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(rentDetil.getIsNewRecord()){
			rentDetil.setZsr(rentDetil.getSrhs());
			rentDetil.setZzc(rentDetil.getZchs());
			rentDetil.setFjsr("0");
			rentDetil.setFjzc("0");
			rentDetil.setFk("0");
			rentDetil.setYfje("0");
			rentDetil.setWfje(rentDetil.getZzc());
		}
		rentDetilService.save(rentDetil);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存仓租收支明细成功");
		return j;
	}
	
	/**
	 * 删除仓租收支明细
	 */
	@ResponseBody
	@RequiresPermissions("infor:rentDetil:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(RentDetil rentDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		rentDetilService.delete(rentDetil);
		j.setMsg("删除仓租收支明细成功");
		return j;
	}

	/**
	 * 付款
	 */
	@ResponseBody
	@RequestMapping(value = "fk")
	public String fk(RentDetil rentDetil,String je, RedirectAttributes redirectAttributes) {
		NumberFormat nf = NumberFormat.getInstance();
		double fkje=Double.parseDouble(je);
		double yfje=Double.parseDouble(rentDetil.getYfje());
		double wfje=Double.parseDouble(rentDetil.getWfje());
		rentDetil.setYfje(nf.format(yfje+fkje).replaceAll(",",""));
		rentDetil.setWfje(nf.format(wfje-fkje).replaceAll(",",""));
		rentDetilService.save(rentDetil);

		return "";
	}
	/**
	 * 确认仓租收支明细
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(RentDetil rentDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		DecimalFormat df = new DecimalFormat("0.00%");
		NumberFormat nf = NumberFormat.getInstance();
		rentDetil.setStatus("已确认");
		rentDetil.setQr(1);
		Sl sl=slService.findUniqueByProperty("pro",rentDetil.getPro());
		sl=slService.get(sl.getId());
		double sj=Double.parseDouble(rentDetil.getZsr())*Double.parseDouble(sl.getSl());
		double mlr=Double.parseDouble(rentDetil.getZsr())-Double.parseDouble(rentDetil.getZzc())-sj;
		double lrl=mlr/Double.parseDouble(rentDetil.getZsr());
		rentDetil.setSj(nf.format(sj).replaceAll(",",""));
		rentDetil.setMlr(nf.format(mlr).replaceAll(",",""));
		rentDetil.setLrl(df.format(lrl));
		rentDetilService.save(rentDetil);
		j.setMsg("确认成功");
		return j;
	}
	/**
	 * 取消确认仓租收支明细
	 */
	@ResponseBody
	@RequestMapping(value = "qxqr")
	public AjaxJson qxqr(RentDetil rentDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		rentDetil.setStatus("已创建");
		rentDetil.setQr(0);
		rentDetil.setMlr("");
		rentDetil.setLrl("");
		rentDetilService.save(rentDetil);
		j.setMsg("取消确认成功");
		return j;
	}

	/**
	 * 批量删除仓租收支明细
	 */
	@ResponseBody
	@RequiresPermissions("infor:rentDetil:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			rentDetilService.delete(rentDetilService.get(id));
		}
		j.setMsg("删除仓租收支明细成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:rentDetil:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(RentDetil rentDetil, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "仓租收支明细"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<RentDetil> page = rentDetilService.findPage(new Page<RentDetil>(request, response, -1), rentDetil);
    		new ExportExcel("仓租收支明细", RentDetil.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出仓租收支明细记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:rentDetil:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<RentDetil> list = ei.getDataList(RentDetil.class);
			for (RentDetil rentDetil : list){
				try{
					rentDetilService.save(rentDetil);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条仓租收支明细记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条仓租收支明细记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入仓租收支明细失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/rentDetil/?repage";
    }
	
	/**
	 * 下载导入仓租收支明细数据模板
	 */
	@RequiresPermissions("infor:rentDetil:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "仓租收支明细数据导入模板.xlsx";
    		List<RentDetil> list = Lists.newArrayList(); 
    		new ExportExcel("仓租收支明细数据", RentDetil.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/rentDetil/?repage";
    }

}